package cn.daniellee.plugin.ice.runnable;

import cn.daniellee.plugin.ice.IceBaoxue;
import cn.daniellee.plugin.ice.core.BaoxueCore;
import cn.daniellee.plugin.ice.model.PlayerData;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

public class BaoxueRunnable extends BukkitRunnable {

    @Override
    public void run() {
        for (Player player : Bukkit.getOnlinePlayers()) {
            if (player != null && (player.hasPermission("ice.use") || player.isOp())) {
                PlayerData playerData = IceBaoxue.getInstance().playerData.get(player.getName());
                if (playerData != null) {
                    if (playerData.isEnable()) {
                        if (playerData.getNextSpit() == 0) {
                            BaoxueCore.useBaoxue(player, playerData.getSuction()); // 来一口
                            playerData.setNextSpit(playerData.getPeriod() - 1); // 重置时间
                        } else playerData.setNextSpit(playerData.getNextSpit() - 1);
                    }
                } else {
                    // 初始化玩家数据
                    int defaultPeriod = IceBaoxue.getInstance().getConfig().getInt("setting.default-period", 60);
	                String defaultSuction = IceBaoxue.getInstance().getConfig().getString("setting.default-suction", "m");
                    playerData = new PlayerData(player.getName(), true, defaultPeriod, defaultSuction);
                    IceBaoxue.getInstance().playerData.put(player.getName(), playerData);
                    IceBaoxue.getInstance().updatePlayerDataYaml(player.getName() + ".enable", true);
                    IceBaoxue.getInstance().updatePlayerDataYaml(player.getName() + ".period", defaultPeriod);
	                IceBaoxue.getInstance().updatePlayerDataYaml(player.getName() + ".suction", defaultSuction);
                }
            }
        }
    }

}
